import 'dart:async';
import 'dart:math';

import 'package:connectfour/record.dart';
import 'package:connectfour/datas.dart';
import 'package:connectfour/welcome.dart';
import 'package:connectfour/win.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class GamePage extends StatefulWidget {
  const GamePage({
    super.key,
  });

  // final String player1;
  // final String player2;

  @override
  State<GamePage> createState() => _GamePageState();
}

class _GamePageState extends State<GamePage> with WidgetsBindingObserver {
  var _seconds = 0;
  var _minute = 0;
  Timer? _timer;
  // bool isTime = false;

  //
  // Future loadString() async {
  //   final prefs = await SharedPreferences.getInstance();
  //   final isTime = prefs.getInt('isTime') ?? 0;
  // }

  Random random = Random();

  List<Offset> piece = [];
  List<Offset> yellowPiece = [];
  List<Offset> redPiece = [];

  List<Widget> firstColumn = [];

  List<Widget> secondColumn = [];
  List<Widget> thirdColumn = [];
  List<Widget> fourthColumn = [];
  List<Widget> fifthColumn = [];
  List<Widget> sixthColumn = [];
  List<Widget> seventhColumn = [];

  List<Color> containerColors1 = [
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white
  ];

  List<Color> containerColors2 = [
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white
  ];
  List<Color> containerColors3 = [
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white
  ];
  List<Color> containerColors4 = [
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white
  ];
  List<Color> containerColors5 = [
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white
  ];
  List<Color> containerColors6 = [
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white
  ];
  List<Color> containerColors7 = [
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white
  ];

  void Q() {
    containerColors1 = [
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white
    ];
    containerColors2 = [
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white
    ];
    containerColors3 = [
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white
    ];
    containerColors4 = [
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white
    ];
    containerColors5 = [
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white
    ];
    containerColors6 = [
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white
    ];
    containerColors7 = [
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white,
      Colors.white
    ];
  }

  void startTimer() {
    if (!isTime) {
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        setState(() {
          _seconds++;
        });
        if (_seconds >= 60) {
          _minute++;
          _seconds = 0;
        }
      });
      isTime = true;
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  List<Color> colorList(List<String> colorStrings, List<Color> colorList) {
    if (colorStrings != null) {
      // 将字符串列表转换为颜色列表
      colorList =
          colorStrings.map((string) => Color(int.parse(string))).toList();
    }
    return colorList;
  }

  Future lS() async {
    print('读取2');
    final prefs = await SharedPreferences.getInstance();
    _minute = prefs.getInt('min') ?? 0;
    _seconds = prefs.getInt('sec') ?? 0;
    List<String>? colorStrings1 = prefs.getStringList('containerColors1');
    List<String>? colorStrings2 = prefs.getStringList('containerColors2');
    List<String>? colorStrings3 = prefs.getStringList('containerColors3');
    List<String>? colorStrings4 = prefs.getStringList('containerColors4');
    List<String>? colorStrings5 = prefs.getStringList('containerColors5');
    List<String>? colorStrings6 = prefs.getStringList('containerColors6');
    List<String>? colorStrings7 = prefs.getStringList('containerColors7');

    containerColors1 = colorList(colorStrings1!, containerColors1);
    containerColors2 = colorList(colorStrings2!, containerColors2);
    containerColors3 = colorList(colorStrings3!, containerColors3);
    containerColors4 = colorList(colorStrings4!, containerColors4);
    containerColors5 = colorList(colorStrings5!, containerColors5);
    containerColors6 = colorList(colorStrings6!, containerColors6);
    containerColors7 = colorList(colorStrings7!, containerColors7);

    List<String>? redPieceX = prefs.getStringList('redPieceX');
    List<String>? redPieceY = prefs.getStringList('redPieceY');
    List<String>? yellowPieceX = prefs.getStringList('yellowPieceX');
    List<String>? yellowPieceY = prefs.getStringList('yellowPieceY');
    List<String>? pieceX = prefs.getStringList('pieceX');
    List<String>? pieceY = prefs.getStringList('pieceY');

    redPiece = offsetList(redPieceX!, redPieceY!);
    yellowPiece = offsetList(yellowPieceX!, yellowPieceY!);
    piece = offsetList(pieceX!, pieceY!);
    print(redPiece);

    suiji();

    setState(() {});
  }

  @override
  void initState() {
    lS();
    WidgetsBinding.instance!.addObserver(this);
    // Random random = Random();
    // int randomNumber = random.nextInt(2);
    // if (randomNumber == 0) {
    //   piece.add(const Offset(0, 0));
    // }
    // print(randomNumber);
    // print(piece);
    // TODO: implement initState
    super.initState();
  }

  List<String> colorString(List<Color> colorList) {
    List<String> colorStrings =
        colorList.map((color) => color.value.toString()).toList();
    return colorStrings;
  }

  List<String> offsetStringX(List<Offset> offsetList) {
    List<String> offsetStringX = [];
    for (var i = 0; i < offsetList.length; i++) {
      offsetStringX.add(offsetList[i].dx.toString());
    }
    return offsetStringX;
  }

  List<String> offsetStringY(List<Offset> offsetList) {
    List<String> offsetStringY = [];
    for (var i = 0; i < offsetList.length; i++) {
      offsetStringY.add(offsetList[i].dy.toString());
    }
    return offsetStringY;
  }

  List<Offset> offsetList(
      List<String> offsetStringX, List<String> offsetStringY) {
    List<Offset> offsetList = [];
    for (var i = 0; i < offsetStringX.length; i++) {
      offsetList.add(Offset(
          double.parse(offsetStringX[i]), double.parse(offsetStringY[i])));
    }
    return offsetList;
  }

  Future saveString() async {
    final prefs = await SharedPreferences.getInstance();

    // await prefs.setString('player1', player1);
    print('存入');
    print(time);
    // await prefs.setBool('isTime', isTime);
    await prefs.setString('player1', player1);
    await prefs.setString('player2', player2);
    await prefs.setString('time', time);
    await prefs.setInt('min', _minute);
    await prefs.setInt('sec', _seconds);
    await prefs.setBool('isStart', isStart);
    // List<String> colorStrings1 = containerColors1.map((color) => color.value.toString()).toList();
    await prefs.setStringList(
        'containerColors1', colorString(containerColors1));
    await prefs.setStringList(
        'containerColors2', colorString(containerColors2));
    await prefs.setStringList(
        'containerColors3', colorString(containerColors3));
    await prefs.setStringList(
        'containerColors4', colorString(containerColors4));
    await prefs.setStringList(
        'containerColors5', colorString(containerColors5));
    await prefs.setStringList(
        'containerColors6', colorString(containerColors6));
    await prefs.setStringList(
        'containerColors7', colorString(containerColors7));
    await prefs.setStringList('redPieceX', offsetStringX(redPiece));
    await prefs.setStringList('redPieceY', offsetStringY(redPiece));
    await prefs.setStringList('yellowPieceX', offsetStringX(yellowPiece));
    await prefs.setStringList('yellowPieceY', offsetStringY(yellowPiece));
    await prefs.setStringList('pieceX', offsetStringX(piece));
    await prefs.setStringList('pieceY', offsetStringY(piece));
  }

  Future _clearSharedPreferences() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.clear();
    print('SharedPreferences data cleared');
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用程序状态变为 AppLifecycleState.paused 时，表示应用即将关闭
    if (state == AppLifecycleState.paused) {
      saveString();
    }
  }

  minString() {
    var m = '0$_minute';
    if (_minute < 10) {
      return m;
    } else {
      return _minute.toString();
    }
  }

  secString() {
    var s = '0$_seconds';
    if (_seconds < 10) {
      return s;
    } else {
      return _seconds.toString();
    }
  }

  suiji() {
    Random random = Random();
    int randomNumber = random.nextInt(2);
    if (randomNumber == 0) {
      piece.add(const Offset(0, 0));
    }
    print(randomNumber);
    print(piece);
  }

  @override
  Widget build(BuildContext context) {
    double zWidth = MediaQuery.of(context).size.width;
    double zHeight = MediaQuery.of(context).size.height;

    setState(() {});
    time = minString() + ' : ' + secString();

    firstColumn = [
      cell(containerColors1[0]),
      cell(containerColors1[1]),
      cell(containerColors1[2]),
      cell(containerColors1[3]),
      cell(containerColors1[4]),
      cell(containerColors1[5])
    ];

    secondColumn = [
      cell(containerColors2[0]),
      cell(containerColors2[1]),
      cell(containerColors2[2]),
      cell(containerColors2[3]),
      cell(containerColors2[4]),
      cell(containerColors2[5])
    ];

    thirdColumn = [
      cell(containerColors3[0]),
      cell(containerColors3[1]),
      cell(containerColors3[2]),
      cell(containerColors3[3]),
      cell(containerColors3[4]),
      cell(containerColors3[5])
    ];

    fourthColumn = [
      cell(containerColors4[0]),
      cell(containerColors4[1]),
      cell(containerColors4[2]),
      cell(containerColors4[3]),
      cell(containerColors4[4]),
      cell(containerColors4[5])
    ];

    fifthColumn = [
      cell(containerColors5[0]),
      cell(containerColors5[1]),
      cell(containerColors5[2]),
      cell(containerColors5[3]),
      cell(containerColors5[4]),
      cell(containerColors5[5])
    ];

    sixthColumn = [
      cell(containerColors6[0]),
      cell(containerColors6[1]),
      cell(containerColors6[2]),
      cell(containerColors6[3]),
      cell(containerColors6[4]),
      cell(containerColors6[5])
    ];

    seventhColumn = [
      cell(containerColors7[0]),
      cell(containerColors7[1]),
      cell(containerColors7[2]),
      cell(containerColors7[3]),
      cell(containerColors7[4]),
      cell(containerColors7[5])
    ];

    // chessGame = [one, two, three, four, five, six, seven];

    var step = 0;

    return Scaffold(
      appBar: AppBar(
        leadingWidth: 100,
        centerTitle: true,
        leading: Padding(
          padding: const EdgeInsets.only(left: 20),
          child: Center(
              child: GestureDetector(
            onTap: () {
              if (isStart) {
                showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (context) {
                      return AlertDialog(
                        title: const Text("提示"),
                        content: const Text(
                            "The game is in progress, are you sure to quit"),
                        actions: [
                          TextButton(
                              onPressed: () async {
                                // Navigator.push(context,
                                //     MaterialPageRoute(builder: (context) {
                                //   return WelcomePage();
                                // }));
                                isTime = false;
                                isStart = false;
                                final prefs =
                                    await SharedPreferences.getInstance();

                                // await prefs.setString('player1', player1);
                                print('存入3');
                                await prefs.setBool('isStart', isStart);
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => WelcomePage(),
                                  ),
                                );
                              },
                              child: const Text("yes")),
                          TextButton(
                              onPressed: () {
                                Navigator.of(context).pop();
                                setState(() {});
                              },
                              child: const Text("no")),
                        ],
                      );
                    });
              } else {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => WelcomePage(),
                  ),
                );
              }
            },
            child: const Text(
              'black',
              style: TextStyle(fontSize: 20),
            ),
          )),
        ),
        title: Container(
            width: 120,
            color: Colors.grey[200],
            child: Center(
                child: Text(
              time,
              style: TextStyle(fontSize: 30),
            ))),
      ),
      body: Row(
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                margin: EdgeInsets.symmetric(
                  horizontal: piece.length % 2 == 0 ? 50 : 40,
                ),
                width: piece.length % 2 == 0 ? 80 : 100,
                height: piece.length % 2 == 0 ? 80 : 100,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(50),
                    color: Colors.yellow),
              ),
              Text(
                player1,
                style: const TextStyle(fontSize: 24),
              ),
            ],
          ),
          Flexible(
              child: Container(
            margin: const EdgeInsets.symmetric(vertical: 40),
            color: Colors.grey[200],
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 80, vertical: 50),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  geCell(firstColumn, containerColors1, 1),
                  geCell(secondColumn, containerColors2, 2),
                  geCell(thirdColumn, containerColors3, 3),
                  geCell(fourthColumn, containerColors4, 4),
                  geCell(fifthColumn, containerColors5, 5),
                  geCell(sixthColumn, containerColors6, 6),
                  geCell(seventhColumn, containerColors7, 7),
                ],
              ),
            ),
          )),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                margin: EdgeInsets.symmetric(
                  horizontal: piece.length % 2 != 0 ? 50 : 40,
                ),
                width: piece.length % 2 != 0 ? 80 : 100,
                height: piece.length % 2 != 0 ? 80 : 100,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(50), color: Colors.red),
              ),
              Text(
                player2,
                style: const TextStyle(fontSize: 24),
              ),
            ],
          ),
        ],
      ),
    );
  }

  GestureDetector geCell(List<Widget> C, List<Color> cc, var x) =>
      GestureDetector(
          onTap: () {
            print('piece$piece');
            startTimer();
            if (!isStart) {
              isStart = !isStart;
            }
            for (var i = C.length - 1; i >= 0; i--) {
              if (cc[i] == Colors.white) {
                if (piece.length % 2 == 0) {
                  C[i] = cell(Colors.red);
                  cc[i] = Colors.red;
                  piece.add(QiZixy(x, (C.length - 1 - i).toDouble()));
                  redPiece.add(QiZixy(x, (C.length - 1 - i).toDouble()));
                  // print('red${QiZixy(x, (C.length - 1 - i).toDouble())}');
                  // print(
                  //     Win(redPiece, QiZixy(x, (C.length - 1 - i).toDouble())));
                  if (Win(redPiece, QiZixy(x, (C.length - 1 - i).toDouble()))) {
                    isTime = false;
                    _timer?.cancel();
                    _clearSharedPreferences();
                    if (isStart) {
                      isStart = !isStart;
                    }
                    showDialog(
                        context: context,
                        barrierDismissible: false,
                        builder: (context) {
                          return AlertDialog(
                            title: const Text("提示"),
                            content: const Text("红方获胜"),
                            actions: [
                              TextButton(
                                  onPressed: () {
                                    recordsList.add(RecordInformation(
                                      datetime: time,
                                      redPlayer: player2,
                                      yellowPlayer: player1,
                                      winner: player2,
                                    ));
                                    _seconds = 0;
                                    _minute = 0;
                                    piece.clear();
                                    yellowPiece.clear();
                                    redPiece.clear();
                                    Q();
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                const RecordPage(
                                                  light: true,
                                                )));
                                    setState(() {});
                                  },
                                  child: const Text("记录")),
                              TextButton(
                                  onPressed: () {
                                    _seconds = 0;
                                    _minute = 0;
                                    piece.clear();
                                    yellowPiece.clear();
                                    redPiece.clear();
                                    Q();
                                    Navigator.of(context).pop();
                                    setState(() {});
                                  },
                                  child: const Text("重新开始")),
                            ],
                          );
                        });
                  }
                  i = C.length - 1;
                } else {
                  C[i] = cell(Colors.yellow);
                  cc[i] = Colors.yellow;
                  piece.add(QiZixy(x, (C.length - 1 - i).toDouble()));
                  yellowPiece.add(QiZixy(x, (C.length - 1 - i).toDouble()));
                  print('yellow${QiZixy(x, (C.length - 1 - i).toDouble())}');
                  if (Win(
                      yellowPiece, QiZixy(x, (C.length - 1 - i).toDouble()))) {
                    isTime = false;
                    _timer?.cancel();
                    _clearSharedPreferences();
                    if (isStart) {
                      isStart = !isStart;
                    }
                    showDialog(
                        context: context,
                        barrierDismissible: false,
                        builder: (context) {
                          return AlertDialog(
                            title: const Text("提示"),
                            content: const Text("黄方获胜"),
                            actions: [
                              TextButton(
                                  onPressed: () {
                                    recordsList.add(RecordInformation(
                                      datetime: time,
                                      redPlayer: player2,
                                      yellowPlayer: player1,
                                      winner: player1,
                                    ));
                                    _seconds = 0;
                                    _minute = 0;
                                    piece.clear();
                                    yellowPiece.clear();
                                    redPiece.clear();
                                    Q();
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                const RecordPage(
                                                  light: true,
                                                )));
                                    setState(() {});
                                  },
                                  child: const Text("记录")),
                              TextButton(
                                  onPressed: () {
                                    _seconds = 0;
                                    _minute = 0;
                                    piece.clear();
                                    yellowPiece.clear();
                                    redPiece.clear();
                                    Q();
                                    Navigator.of(context).pop();
                                    setState(() {});
                                  },
                                  child: const Text("重新开始")),
                            ],
                          );
                        });
                  }
                  i = C.length - 1;
                }
                break;
              }
            }
            setState(() {});
          },
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: C,
          ));

  Offset QiZixy(var dx, double dy) {
    double ddx = 0; //最终棋子的x坐标
    // double ddy = dy.toDouble;

    switch (dx) {
      case 1:
        ddx = 0;
        break;
      case 2:
        ddx = 1;
        break;
      case 3:
        ddx = 2;
        break;
      case 4:
        ddx = 3;
        break;
      case 5:
        ddx = 4;
        break;
      case 6:
        ddx = 5;
        break;
      case 7:
        ddx = 6;
        break;
    }

    return Offset(ddx, dy);
  }
}

Container cell(Color color) {
  return Container(
    width: 80,
    height: 80,
    decoration:
        BoxDecoration(borderRadius: BorderRadius.circular(40), color: color),
  );
}
